package dk.marten;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
import android.hardware.Sensor;
import android.hardware.SensorManager;

public class Main extends Activity {

	private SensorManager sensorManager;
	private Sensor sensor;
	private LocationManager mlocManager;
	LocationListener mlocListener;
	private float x, y, z;
	private boolean useAccSensor = false;
	BallView bv;
	SharedPreferences sharedPreferences;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		// Remove title bar
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		// Remove notification bar
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);


		sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); 
//		sharedPreferences = getPreferences(MODE_PRIVATE);
		
		bv = new BallView(this);
		bv.sharedPreferences = sharedPreferences;
		setContentView(bv);

		sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		useAccSensor = !sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER).isEmpty();
		if(useAccSensor) sensor = sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);

		mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
		mlocListener = new MyLocationListener(); 
		mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);

        loadPreferences();
	}

	@Override
	protected void onResume() {
		Log.d("Main", "onResume");
		super.onResume();
		if(useAccSensor) sensorManager.registerListener(accelerationListener, sensor, SensorManager.SENSOR_DELAY_GAME);
		mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
	}

	@Override
	protected void onStop() {
		Log.d("Main", "onStop");
		super.onStop();
		if(useAccSensor) sensorManager.unregisterListener(accelerationListener);
		mlocManager.removeUpdates(mlocListener);
	}

	@Override
	public void onStart() {
		Log.d("Main", "onStart");
		super.onStart();
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0,0,0,"Clear");
		MenuItem im = menu.add(0,1,0,"Help");
		//im.setIcon(R.drawable.icon);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 0:
			bv.clear();
			Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
			long[] pattern = { 0, 50, 50 , 50};
			 try {
			v.vibrate(pattern, -1);
			 } catch (Exception e) {
				 Log.e("Vibrator",e.toString());				 
			 }
			break;
		case 1:
			Intent myIntent = new Intent(Main.this, HelpPage.class);
			startActivity(myIntent);
			break;
		}
		return true;
	}



	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
		savedInstanceState.putFloatArray("smallDotX", bv.getSmallDotPos(true));
		savedInstanceState.putFloatArray("smallDotY", bv.getSmallDotPos(false));

		savedInstanceState.putFloatArray("posistion", bv.getPosition());
		savedInstanceState.putFloatArray("acceleration", bv.getAcc());
		savedInstanceState.putFloatArray("speed", bv.getSpeed());

		super.onSaveInstanceState(savedInstanceState);
	}

	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		if (savedInstanceState != null) {
			bv.setPosition(savedInstanceState.getFloatArray("posistion"));
			bv.setAcc(savedInstanceState.getFloatArray("acceleration"));
			bv.setSpeed(savedInstanceState.getFloatArray("speed"));
			bv.setSmallDotPos(savedInstanceState.getFloatArray("smallDotX"),savedInstanceState.getFloatArray("smallDotY"));
		}
	}

    private void loadPreferences(){
        SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
        bv.targetHue = sharedPreferences.getFloat("TargetHue", 1f);
        bv.currentHue = sharedPreferences.getFloat("CurrentHue", 0f);
    }
    


	private SensorEventListener accelerationListener = new SensorEventListener() {
		@Override
		public void onAccuracyChanged(Sensor sensor, int acc) {
		}

		@Override
		public void onSensorChanged(SensorEvent event) {
			x = event.values[0];
			y = event.values[1];
			z = event.values[2];
			bv.sensorUpdate(x, y, z);
		}
	};


	/* Class My Location Listener */ 

	public class MyLocationListener implements LocationListener { 

		@Override 
		public void onLocationChanged(Location loc) { 
			double latRest = (loc.getLatitude()*100)%1;
            double longRest = (loc.getLongitude()*100)%1;
            if (latRest>0.5) latRest -= 0.5;
            if (longRest>0.5) longRest -= 0.5;
            double dist = Math.sqrt(latRest*latRest + longRest*longRest)/Math.sqrt(0.5);
            
			 bv.targetHue = (float) (dist*360);
			 SharedPreferences.Editor editor = sharedPreferences.edit();
             editor.putFloat("TargetHue", bv.targetHue);
             editor.commit();
             
		} 

		@Override 
		public void onProviderDisabled(String provider) { 
		} 

		@Override 
		public void onProviderEnabled(String provider) {
		} 

		@Override 
		public void onStatusChanged(String provider, int status, Bundle extras) { 

		} 

	}




}